#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@file: obs_gk_video_recording.py
@author: lyndon
@time: Created on 2022-02-19 20:07
@env: Python
@desc:
@ref:
@blog:
"""


import sys
import time
import logging
from selenium import webdriver
from selenium.webdriver.common.by import By

logging.basicConfig(level=logging.INFO)


sys.path.append('../')
from obswebsocket import obsws, requests  # noqa: E402


host = "localhost"
port = 4444
password = "secret"

ws = obsws(host, port, password)
ws.connect()
max_retry_time = 3


def record(offon, retry_times=0):
    if offon == "start":
        try:
            ws.call(requests.StartRecording())
        except KeyboardInterrupt:
            if retry_times < max_retry_time:
                retry_times = retry_times + 1
                record(offon, retry_times)
    elif offon == "stop":
        try:
            ws.call(requests.StopRecording())
        except KeyboardInterrupt:
            if retry_times < max_retry_time:
                retry_times = retry_times + 1
                record(offon, retry_times)


if __name__ == '__main__':
    numbers = 1
    maxNumbers = 22
    browser = webdriver.Chrome("D:\iSoft\chromedriver_win32\chromedriver.exe")
    time.sleep(0.5)
    # browser.get("https://wxtime.geekbang.org/course/intro/100060601?tab=catalog")
    browser.get("https://wxtime.geekbang.org/course/intro/100019701?tab=catalog")
    time.sleep(30)  # 等待页面加载, 扫码登录，手动点击到课程页
    while True:
        try:
            f = browser.find_element(By.CLASS_NAME, 'GkPlayer_fullscreenOffBtn_3ZIlN')
            f.click()  # 全屏
            break
        except Exception as e:
            time.sleep(2)
            continue
    # time.sleep(2)
    while True:
        try:
            w = browser.find_element(By.CLASS_NAME, "GkPlayer_bigPlayIcon_1uopO")
            w.click()
            break
        except Exception as e:
            time.sleep(2)
            continue
    time.sleep(10)
    record('start')
    while True:
        print("listening...{}.finish.".format(numbers))
        try:
            time.sleep(5)
            w = browser.find_element(By.CLASS_NAME, "GkPlayer_bigPlayIcon_1uopO")
            # TODO 不断扫描是否弹出播放按钮，代表播放结束了，需要： 停止录制 -> 等待5秒 -> 点击全屏 -> 开始录制 -> 点击播放，再不断监听播放按钮
            record('stop')
            # time.sleep(5)
            f = browser.find_element(By.CLASS_NAME, 'GkPlayer_fullscreenOffBtn_3ZIlN')
            f.click()  # 全屏
            record('start')
            w.click()
        except Exception as e:
            continue
        numbers += 1
        if numbers >= maxNumbers:
            print('stop')
            break

    time.sleep(30)
    # 退出
    browser.close()
    browser.quit()

    ws.disconnect()
